import React, { useEffect, useState, useRef, useCallback } from 'react'
import { 
  Card, 
  Input, 
  Button, 
  Space, 
  Select, 
  message, 
  Spin, 
  Badge, 
  Tooltip, 
  Modal, 
  Drawer,
  Tabs,
  Dropdown,
  Menu,
  Row,
  Col,
  Tag,
  Progress,
  Alert,
  Divider,
  Typography,
  Empty,
  Result
} from 'antd'
import { 
  SaveOutlined, 
  SendOutlined, 
  SettingOutlined, 
  ReloadOutlined, 
  CheckCircleOutlined, 
  ExclamationCircleOutlined, 
  QuestionCircleOutlined,
  ThunderboltOutlined,
  BookOutlined,
  EditOutlined,
  ExperimentOutlined,
  BarChartOutlined,
  SwapOutlined,
  BulbOutlined,
  FileTextOutlined,
  DownloadOutlined,
  FireOutlined,
  SafetyCertificateOutlined,
  DashboardOutlined,
  HistoryOutlined,
  CopyOutlined,
  RobotOutlined,
  CommentOutlined,
  ShareAltOutlined,
  PlusOutlined,
  StarOutlined,
  FilterOutlined,
  SwapOutlined as CompareOutlined
} from '@ant-design/icons'

// Store imports
import { useModelConfigStore } from '../../stores/model-config.store'
import { usePromptStore } from '../../stores/prompt.store'
import { useConversationStore } from '../../stores/conversation.store'
import { useHotRadarStore } from '../../stores/hotRadar.store'
import { useTemplateStore } from '../../stores/template.store'

// Component imports - 提示词管理
import PromptSelector from '../../components/conversation/PromptSelector'
import PromptEditor from '../../components/conversation/PromptEditor'
import PromptLibrary from '../../components/conversation/PromptLibrary'
import PromptTester from '../../components/conversation/PromptTester'
import PromptStatistics from '../../components/conversation/PromptStatistics'
import PromptVersionHistory from '../../components/conversation/PromptVersionHistory'
import VariableForm from '../../components/conversation/VariableForm'

// Component imports - 模型管理
import ModelComparison from '../../components/conversation/ModelComparison'
import ModelSelector from '../../components/conversation/ModelSelector'
import ParameterPanel from '../../components/conversation/ParameterPanel'
import ModelStatusIndicator from '../../components/conversation/ModelStatusIndicator'

// Component imports - 内容优化
import OptimizationPanel from '../../components/optimization/OptimizationPanel'

// Component imports - 热点创作
import HotTopicPanel from '../../components/conversation/HotTopicPanel'

// Services
import { generationService } from '../../services/generation.service'
import { aiGenerationService } from '../../services/ai-generation.service'

const { TextArea } = Input
const { Option } = Select
const { TabPane } = Tabs
const { Title, Text, Paragraph } = Typography

interface HotTopicContext {
  id: string
  title: string
  platform: string
  heat: number
  summary: string
  comments?: string[]
  relatedTopics?: string[]
}

const HotCreatorEditor: React.FC = () => {
  // ========== State Management ==========
  // Store hooks
  const { configs, loading: modelsLoading, loadConfigs } = useModelConfigStore()
  const { 
    prompts, 
    currentPrompt, 
    loadPrompts, 
    selectPrompt,
    createPrompt,
    updatePrompt
  } = usePromptStore()
  const {
    sendMessage,
    isGenerating,
    messages,
    clearMessages
  } = useConversationStore()
  const {
    hotItems
  } = useHotRadarStore()

  // 模板store
  const {
    templates,
    applyTemplate,
    loadTemplates
  } = useTemplateStore()

  // Local state - 基础状态
  const [selectedModel, setSelectedModel] = useState<string>('')
  const [title, setTitle] = useState('')
  const [content, setContent] = useState('')
  const [generatedContent, setGeneratedContent] = useState('')
  const [activeTab, setActiveTab] = useState('create')
  const [editorMode, setEditorMode] = useState<'simple' | 'advanced'>('simple')
  
  // Local state - 热点相关
  const [hotTopicContext, setHotTopicContext] = useState<HotTopicContext | null>(null)
  const [hotTopicPrompt, setHotTopicPrompt] = useState('')
  const [writingAngle, setWritingAngle] = useState<string>('comprehensive_analysis')
  const [writingAngles, setWritingAngles] = useState<{writing_angles: string[], descriptions: Record<string, string>}>({
    writing_angles: [],
    descriptions: {}
  })
  
  // Local state - 质量评估
  const [qualityScore, setQualityScore] = useState<number | null>(null)
  const [originalityScore, setOriginalityScore] = useState<number | null>(null)
  const [isCheckingQuality, setIsCheckingQuality] = useState(false)
  
  // Local state - 参数控制
  const [parameters, setParameters] = useState({
    temperature: 0.7,
    maxTokens: 2000,
    topP: 0.9,
    frequencyPenalty: 0,
    presencePenalty: 0,
    stream: true
  })
  
  // Local state - UI控制
  const [promptLibraryVisible, setPromptLibraryVisible] = useState(false)
  const [promptEditorVisible, setPromptEditorVisible] = useState(false)
  const [promptTesterVisible, setPromptTesterVisible] = useState(false)
  const [promptHistoryVisible, setPromptHistoryVisible] = useState(false)
  const [modelComparisonVisible, setModelComparisonVisible] = useState(false)
  const [hotTopicVisible, setHotTopicVisible] = useState(false)
  const [parameterPanelVisible, setParameterPanelVisible] = useState(false)
  const [templateSelectorVisible, setTemplateSelectorVisible] = useState(false)
  const [selectedTemplate, setSelectedTemplate] = useState<any>(null)
  
  // Refs
  const autoSaveTimer = useRef<NodeJS.Timeout>()
  const generationAbortController = useRef<AbortController>()

  // ========== Lifecycle & Effects ==========
  useEffect(() => {
    // 初始化加载
    loadConfigs()
    loadPrompts()
    loadTemplates()
    // 加载写作角度选项
    loadWritingAngles()
  }, [loadConfigs, loadPrompts, loadTemplates])
  
  // 加载写作角度
  const loadWritingAngles = async () => {
    try {
      const angles = await aiGenerationService.getWritingAngles()
      setWritingAngles(angles)
    } catch (error) {
      console.error('Failed to load writing angles:', error)
    }
  }

  // 自动选择第一个可用模型
  useEffect(() => {
    const availableModels = configs.filter(c => c.isActive && c.status === 'healthy')
    if (!selectedModel && availableModels.length > 0) {
      setSelectedModel(availableModels[0].id)
    }
  }, [configs, selectedModel])

  // 自动保存草稿
  useEffect(() => {
    if (content || generatedContent) {
      autoSaveTimer.current = setTimeout(() => {
        saveDraft()
      }, 30000) // 30秒自动保存
    }
    return () => {
      if (autoSaveTimer.current) {
        clearTimeout(autoSaveTimer.current)
      }
    }
  }, [content, generatedContent, title])

  // ========== Helper Functions ==========
  const getAvailableModels = () => {
    return configs.filter(c => c.isActive === true)
  }

  const getHealthyModels = () => {
    return getAvailableModels().filter(c => c.status === 'healthy')
  }

  const saveDraft = () => {
    const draft = {
      title,
      content,
      generatedContent,
      selectedModel,
      currentPrompt: currentPrompt?.id,
      parameters,
      hotTopicContext,
      timestamp: new Date().toISOString()
    }
    localStorage.setItem('editor-draft', JSON.stringify(draft))
    message.success('草稿已自动保存', 1)
  }

  const loadDraft = () => {
    const draftStr = localStorage.getItem('editor-draft')
    if (draftStr) {
      try {
        const draft = JSON.parse(draftStr)
        setTitle(draft.title || '')
        setContent(draft.content || '')
        setGeneratedContent(draft.generatedContent || '')
        setSelectedModel(draft.selectedModel || '')
        setParameters(draft.parameters || parameters)
        setHotTopicContext(draft.hotTopicContext || null)
        if (draft.currentPrompt) {
          selectPrompt(draft.currentPrompt)
        }
        message.success('草稿已恢复')
      } catch (error) {
        message.error('草稿恢复失败')
      }
    }
  }

  // ========== Core Functions ==========
  
  // 处理热点选择
  const handleHotTopicSelect = useCallback((topic: any) => {
    setHotTopicContext({
      id: topic.id,
      title: topic.title,
      platform: topic.platform,
      heat: topic.heat || topic.hotValue,
      summary: topic.summary || '',
      comments: topic.comments,
      relatedTopics: topic.relatedTopics
    })
    
    // 生成热点相关的提示词
    const hotPrompt = `请基于以下热点话题创作内容：

热点标题：${topic.title}
平台来源：${topic.platform}
热度值：${topic.heat || topic.hotValue}
话题摘要：${topic.summary || ''}

请创作一篇有见解、有深度的文章，包含：
1. 对热点事件的分析
2. 多角度的观点阐述
3. 相关背景信息
4. 你的独特见解`

    setContent(hotPrompt)
    setHotTopicPrompt(hotPrompt)
    setHotTopicVisible(false)
    
    message.success('已加载热点话题，可以开始创作了！')
  }, [])

  // 处理生成内容
  const handleGenerate = async () => {
    if (!selectedModel) {
      message.warning('请先选择AI模型')
      return
    }
    if (!content.trim() && !hotTopicContext) {
      message.warning('请输入创作内容或选择热点话题')
      return
    }

    try {
      // 准备中断控制器
      generationAbortController.current = new AbortController()
      
      // 如果有热点上下文，使用新的 LangChain 热点创作 API
      if (hotTopicContext) {
        // 清空之前的内容
        setGeneratedContent('')
        
        // 使用流式生成
        if (parameters.stream) {
          let fullContent = ''
          console.log('开始流式生成，热点ID:', hotTopicContext.id)
          await aiGenerationService.generateHotContentStream(
            hotTopicContext.id,
            hotTopicContext.platform,
            writingAngle,
            content || undefined,
            selectedModel,
            parameters,
            // onChunk: 处理流式内容块
            (chunk: string) => {
              console.log('收到内容块:', chunk)
              fullContent += chunk
              console.log('累积内容长度:', fullContent.length)
              setGeneratedContent(fullContent)
            },
            // onComplete: 生成完成
            (metadata: any) => {
              console.log('生成完成，最终内容长度:', fullContent.length)
              console.log('最终内容:', fullContent)
              checkContentQuality(fullContent)
              message.success('热点内容生成完成！')
              console.log('Generation metadata:', metadata)
            },
            // onError: 错误处理
            (error: Error) => {
              console.error('生成错误:', error)
              message.error('生成失败：' + error.message)
            }
          )
        } else {
          // 非流式生成
          const result = await aiGenerationService.generateHotContent(
            hotTopicContext.id,
            hotTopicContext.platform,
            writingAngle,
            content || undefined,
            selectedModel,
            parameters
          )
          
          setGeneratedContent(result.content)
          checkContentQuality(result.content)
          message.success('热点内容生成完成！')
        }
      } else {
        // 没有热点上下文时，使用普通生成
        let finalPrompt = content
        if (currentPrompt) {
          // 如果有系统提示词，结合使用
          finalPrompt = `${currentPrompt.systemPrompt}\n\n用户输入：${content}`
        }

        // 获取选中的模型配置
        console.log('Selected model ID:', selectedModel)
        console.log('Available configs:', configs)
        
        const modelConfig = configs.find(c => c.id === selectedModel)
        if (!modelConfig) {
          message.error(`未找到模型配置: ${selectedModel}`)
          return
        }
        
        console.log('Found model config:', modelConfig)
        
        // 检查必要的配置字段
        if (!modelConfig.apiBase && !modelConfig.baseUrl) {
          message.error('模型配置缺少API地址')
          return
        }
        
        if (!modelConfig.apiKey) {
          message.error('模型配置缺少API密钥')
          return
        }

        // 调用生成服务
        const result = await aiGenerationService.generateWithConfig(
          modelConfig,
          finalPrompt,
          parameters
        )

        setGeneratedContent(result.content)
        
        // 自动进行质量检查
        checkContentQuality(result.content)
        
        message.success('内容生成完成！')
      }
    } catch (error: any) {
      if (error.name === 'AbortError') {
        message.info('生成已取消')
      } else {
        message.error('生成失败：' + error.message)
      }
    }
  }

  // 停止生成
  const handleStopGeneration = () => {
    if (generationAbortController.current) {
      generationAbortController.current.abort()
      message.info('正在停止生成...')
    }
  }

  // 检查内容质量
  const checkContentQuality = async (text: string) => {
    setIsCheckingQuality(true)
    try {
      // 这里应该调用实际的质量检测API
      // 暂时使用模拟数据
      setTimeout(() => {
        setQualityScore(Math.floor(Math.random() * 20) + 75)
        setOriginalityScore(Math.floor(Math.random() * 15) + 80)
        setIsCheckingQuality(false)
      }, 2000)
    } catch (error) {
      message.error('质量检测失败')
      setIsCheckingQuality(false)
    }
  }

  // 处理提示词选择
  const handlePromptSelect = (template: any) => {
    console.log('=== Prompt Selected ===')
    console.log('Template:', template)
    console.log('Template systemPrompt:', template.systemPrompt)

    selectPrompt(template.id)

    // 如果有变量，显示变量表单
    if (template.variables && template.variables.length > 0) {
      Modal.info({
        title: '配置提示词变量',
        content: (
          <VariableForm
            variables={template.variables}
            onSubmit={(values) => {
              // 替换变量生成最终提示词
              let processedPrompt = template.systemPrompt
              Object.keys(values).forEach(key => {
                processedPrompt = processedPrompt.replace(new RegExp(`{${key}}`, 'g'), values[key])
              })
              console.log('Processed prompt with variables:', processedPrompt)
              setContent(processedPrompt)
              Modal.destroyAll()
            }}
          />
        ),
        width: 600,
        okText: '确定'
      })
    } else {
      // 直接将提示词内容填充到输入框
      const promptContent = template.systemPrompt || template.content || ''
      console.log('Setting content to:', promptContent)
      setContent(promptContent)
    }

    setPromptLibraryVisible(false)
    message.success(`已选择提示词：${template.name}`)
  }

  // 处理模型切换
  const handleModelChange = (value: string) => {
    setSelectedModel(value)
    const model = configs.find(c => c.id === value)
    if (model) {
      message.info(`已切换到模型：${model.displayName || model.modelName}`)
    }
  }

  // 处理多模型对比
  const handleModelComparison = () => {
    if (!content.trim()) {
      message.warning('请先输入要生成的内容')
      return
    }
    setModelComparisonVisible(true)
  }

  // 应用模板
  const handleApplyTemplate = (template: any) => {
    setSelectedTemplate(template)

    // 如果模板有变量，显示变量填充表单
    if (template.variables && template.variables.length > 0) {
      Modal.confirm({
        title: `使用模板：${template.name}`,
        width: 600,
        content: (
          <div>
            <p>此模板包含 {template.variables.length} 个变量，是否直接应用模板框架？</p>
            <p style={{ color: '#999', fontSize: '12px' }}>
              应用后可以在编辑框中手动填充变量内容
            </p>
          </div>
        ),
        onOk: () => {
          setContent(template.content)
          setTemplateSelectorVisible(false)
          message.success(`已应用模板：${template.name}`)
        }
      })
    } else {
      setContent(template.content)
      setTemplateSelectorVisible(false)
      message.success(`已应用模板：${template.name}`)
    }
  }

  // 导出内容
  const handleExport = (format: 'md' | 'html' | 'docx' | 'pdf') => {
    if (!generatedContent) {
      message.warning('没有可导出的内容')
      return
    }
    
    // 这里应该调用实际的导出服务
    message.info(`正在导出为 ${format.toUpperCase()} 格式...`)
  }

  // ========== UI Components ==========
  
  // 工具栏菜单
  const toolsMenu = (
    <Menu>
      <Menu.ItemGroup title="提示词工具">
        <Menu.Item 
          key="prompt-library" 
          icon={<BookOutlined />}
          onClick={() => setPromptLibraryVisible(true)}
        >
          提示词库
        </Menu.Item>
        <Menu.Item 
          key="prompt-editor" 
          icon={<EditOutlined />}
          onClick={() => setPromptEditorVisible(true)}
        >
          编辑提示词
        </Menu.Item>
        <Menu.Item 
          key="prompt-test" 
          icon={<ExperimentOutlined />}
          onClick={() => setPromptTesterVisible(true)}
        >
          测试提示词
        </Menu.Item>
        <Menu.Item 
          key="prompt-history" 
          icon={<HistoryOutlined />}
          onClick={() => setPromptHistoryVisible(true)}
        >
          版本历史
        </Menu.Item>
      </Menu.ItemGroup>
      
      <Menu.Divider />
      
      <Menu.ItemGroup title="生成工具">
        <Menu.Item 
          key="model-comparison" 
          icon={<CompareOutlined />}
          onClick={handleModelComparison}
        >
          多模型对比
        </Menu.Item>
        <Menu.Item 
          key="parameter-settings" 
          icon={<SettingOutlined />}
          onClick={() => setParameterPanelVisible(true)}
        >
          参数设置
        </Menu.Item>
      </Menu.ItemGroup>
      
      <Menu.Divider />

      <Menu.ItemGroup title="内容优化">
        <Menu.Item
          key="optimization"
          icon={<BulbOutlined />}
          onClick={() => {
            if (!generatedContent) {
              message.warning('请先生成内容后再使用优化功能')
            } else {
              message.info('优化功能已在主页面右侧显示')
            }
          }}
          disabled={!generatedContent}
        >
          智能优化
        </Menu.Item>
        <Menu.Item
          key="quality-check"
          icon={<SafetyCertificateOutlined />}
          onClick={() => checkContentQuality(generatedContent)}
          disabled={!generatedContent}
        >
          质量检测
        </Menu.Item>
      </Menu.ItemGroup>
    </Menu>
  )

  // 导出菜单
  const exportMenu = (
    <Menu>
      <Menu.Item key="md" onClick={() => handleExport('md')}>
        Markdown (.md)
      </Menu.Item>
      <Menu.Item key="html" onClick={() => handleExport('html')}>
        HTML (.html)
      </Menu.Item>
      <Menu.Item key="docx" onClick={() => handleExport('docx')}>
        Word (.docx)
      </Menu.Item>
      <Menu.Item key="pdf" onClick={() => handleExport('pdf')}>
        PDF (.pdf)
      </Menu.Item>
    </Menu>
  )

  // 热点话题卡片
  const renderHotTopicCard = () => {
    if (!hotTopicContext) return null

    return (
      <Card
        size="small"
        className="mb-3"
        title={
          <Space size="small">
            <FireOutlined style={{ color: '#ff4d4f' }} />
            <Text strong className="text-sm md:text-base">
              <span className="hidden sm:inline">当前热点话题</span>
              <span className="sm:hidden">热点</span>
            </Text>
          </Space>
        }
        extra={
          <Button
            size="small"
            onClick={() => setHotTopicContext(null)}
          >
            清除
          </Button>
        }
      >
        <Space direction="vertical" size="small" className="w-full">
          <Text strong className="text-sm">{hotTopicContext.title}</Text>
          <Space size="small" wrap>
            <Tag color="blue" className="text-xs">{hotTopicContext.platform}</Tag>
            <Tag color="red" className="text-xs">热度: {hotTopicContext.heat}</Tag>
          </Space>
          {hotTopicContext.summary && (
            <Paragraph
              ellipsis={{ rows: 2, expandable: true }}
              style={{ marginBottom: 0, fontSize: '13px' }}
              className="text-gray-600"
            >
              {hotTopicContext.summary}
            </Paragraph>
          )}

          {/* 写作角度选择 */}
          <div className="w-full mt-2">
            <Text type="secondary" className="mr-2 text-xs md:text-sm">写作角度：</Text>
            <Select
              value={writingAngle}
              onChange={setWritingAngle}
              style={{ width: '100%' }}
              placeholder="选择写作角度"
            >
              {writingAngles.writing_angles.map(angle => (
                <Option key={angle} value={angle}>
                  <Tooltip title={writingAngles.descriptions[angle]}>
                    {angle === 'news_report' && '📰 新闻报道'}
                    {angle === 'comprehensive_analysis' && '📊 综合分析'}
                    {angle === 'emotional_resonance' && '💭 情感共鸣'}
                    {angle === 'humorous_satire' && '😄 幽默讽刺'}
                    {angle === 'technical_interpretation' && '🔬 技术解读'}
                    {angle === 'opposing_perspective' && '🔄 反向观点'}
                    {angle === 'personal_experience' && '👤 个人经历'}
                    {angle === 'future_prediction' && '🔮 未来预测'}
                    {!['news_report', 'comprehensive_analysis', 'emotional_resonance', 'humorous_satire', 
                      'technical_interpretation', 'opposing_perspective', 'personal_experience', 'future_prediction'].includes(angle) && angle}
                  </Tooltip>
                </Option>
              ))}
            </Select>
          </div>
        </Space>
      </Card>
    )
  }

  // 质量评分展示
  const renderQualityScore = () => {
    if (!qualityScore && !originalityScore) return null
    
    return (
      <Card size="small" className="mb-4">
        <Space direction="vertical" className="w-full">
          <Text strong>内容质量评估</Text>
          <Row gutter={16}>
            <Col span={12}>
              <Text type="secondary">质量评分</Text>
              <Progress 
                percent={qualityScore || 0} 
                status={qualityScore! >= 80 ? 'success' : qualityScore! >= 60 ? 'normal' : 'exception'}
              />
            </Col>
            <Col span={12}>
              <Text type="secondary">原创度</Text>
              <Progress 
                percent={originalityScore || 0}
                status={originalityScore! >= 80 ? 'success' : originalityScore! >= 60 ? 'normal' : 'exception'}
              />
            </Col>
          </Row>
        </Space>
      </Card>
    )
  }

  // ========== Main Render ==========
  return (
    <div className="hot-creator-editor h-full pb-20 md:pb-4">
      {/* Header */}
      <div className="editor-header mb-4 p-3 md:p-4 bg-white rounded-lg shadow-sm">
        <div className="flex flex-col md:flex-row md:justify-between md:items-center gap-3">
          <div className="flex items-center flex-wrap gap-2">
            <Title level={3} className="m-0 text-base md:text-xl">
              <FireOutlined className="mr-2" style={{ color: '#ff4d4f' }} />
              <span className="hidden sm:inline">AI热点创作编辑器</span>
              <span className="sm:hidden">热点创作</span>
            </Title>
            {hotTopicContext && (
              <Tag color="red" icon={<FireOutlined />} className="text-xs">
                <span className="hidden sm:inline">正在创作热点内容</span>
                <span className="sm:hidden">热点</span>
              </Tag>
            )}
          </div>
        
        <div className="flex flex-col md:flex-row gap-2 mt-3 md:mt-0">
          {/* 移动端第一行按钮 */}
          <div className="flex gap-2 w-full md:w-auto">
            {/* 热点创作入口 */}
            <Button 
              type="primary"
              icon={<FireOutlined />} 
              onClick={() => setHotTopicVisible(true)}
              danger
              className="flex-1 md:flex-none"
            >
              <span className="hidden sm:inline">选择热点</span>
              <span className="sm:hidden">热点</span>
            </Button>
            
            {/* AI工具箱 */}
            <Dropdown overlay={toolsMenu} trigger={['click']}>
              <Button icon={<ThunderboltOutlined />} className="flex-1 md:flex-none">
                <span className="hidden sm:inline">AI工具箱</span>
                <span className="sm:hidden">工具</span>
              </Button>
            </Dropdown>
          </div>
          
          {/* 移动端第二行 - 模型选择和草稿 */}
          <div className="flex gap-2 w-full md:w-auto">
            {/* 模型选择 */}
            <Select
              value={selectedModel}
              onChange={handleModelChange}
              className="flex-1 md:flex-none"
              style={{ minWidth: '120px' }}
              placeholder="选择AI模型"
              loading={modelsLoading}
            >
            {getHealthyModels().map(config => (
              <Option key={config.id} value={config.id}>
                <Space>
                  <ModelStatusIndicator status={config.status} />
                  {config.displayName || config.modelName}
                </Space>
              </Option>
            ))}
            </Select>
            
            {/* 草稿管理 */}
            <Button.Group className="flex md:flex-none">
              <Button icon={<SaveOutlined />} onClick={saveDraft} className="flex-1">
                <span className="hidden sm:inline">保存</span>
              </Button>
              <Button onClick={loadDraft} className="flex-1">
                <span className="hidden sm:inline">恢复</span>
              </Button>
            </Button.Group>
          </div>
        </div>
        </div>
      </div>

      {/* Main Content */}
      <div className="editor-content">
        <Tabs 
          activeKey={activeTab} 
          onChange={setActiveTab}
          type="card"
          className="h-full"
        >
          {/* 创作标签页 */}
          <TabPane
            tab={
              <Space>
                <EditOutlined />
                <span>创作</span>
              </Space>
            }
            key="create"
          >
            <Row gutter={[16, 16]} className="h-full">
              {/* 左侧输入区 */}
              <Col xs={24} lg={8}>
                <Card
                  title={
                    <Space>
                      <Text strong>输入区</Text>
                      {currentPrompt && (
                        <Tag color="green">{currentPrompt.name}</Tag>
                      )}
                      {selectedTemplate && (
                        <Tag color="blue" icon={<FileTextOutlined />}>
                          {selectedTemplate.name}
                        </Tag>
                      )}
                    </Space>
                  }
                  extra={
                    <Space>
                      <PromptSelector
                        onSelect={handlePromptSelect}
                        showQuickActions={false}
                      />
                      <Tooltip title="选择模板">
                        <Button
                          size="small"
                          icon={<FileTextOutlined />}
                          onClick={() => setTemplateSelectorVisible(true)}
                        >
                          模板
                        </Button>
                      </Tooltip>
                      <Button
                        size="small"
                        icon={<CopyOutlined />}
                        onClick={() => {
                          navigator.clipboard.writeText(content)
                          message.success('已复制')
                        }}
                        className="hidden sm:inline-flex"
                      >
                        复制
                      </Button>
                      <Button
                        size="small"
                        icon={<CopyOutlined />}
                        onClick={() => {
                          navigator.clipboard.writeText(content)
                          message.success('已复制')
                        }}
                        className="sm:hidden"
                      />
                    </Space>
                  }
                  className="h-full lg:h-full"
                  bodyStyle={{ minHeight: '400px' }}
                >
                  {renderHotTopicCard()}

                  <Input
                    placeholder="输入文章标题..."
                    size="large"
                    value={title}
                    onChange={(e) => setTitle(e.target.value)}
                    className="mb-3"
                  />

                  <div>
                    <Alert
                      message="创作输入格式提示"
                      description={
                        <div style={{ fontSize: '12px' }}>
                          <p><strong>方式1：直接描述需求</strong></p>
                          <p style={{ marginBottom: 8 }}>示例：请写一篇关于人工智能发展的深度分析文章，要求观点客观、论据充分</p>

                          <p><strong>方式2：结合热点创作（推荐）</strong></p>
                          <p style={{ marginBottom: 8 }}>1. 点击"选择热点"按钮选择热门话题</p>
                          <p style={{ marginBottom: 8 }}>2. 系统会自动填充热点信息到输入框</p>
                          <p style={{ marginBottom: 8 }}>3. 可选：添加个性化要求，如"请从技术角度分析"</p>

                          <p><strong>方式3：使用提示词库</strong></p>
                          <p style={{ marginBottom: 0 }}>点击"提示词"按钮，选择专业模板快速开始创作</p>
                        </div>
                      }
                      type="info"
                      closable
                      style={{ marginBottom: 12 }}
                    />

                    <TextArea
                      placeholder="在这里输入您的创作内容或提示词..."
                      value={content}
                      onChange={(e) => setContent(e.target.value)}
                      rows={8}
                      style={{ resize: 'vertical', textAlign: 'right', direction: 'rtl' }}
                    />
                  </div>
                </Card>
              </Col>

              {/* 中间生成区 */}
              <Col xs={24} lg={8}>
                <Card
                  title={
                    <Space>
                      <Text strong>生成内容</Text>
                      {isGenerating && <Spin size="small" />}
                      {isCheckingQuality && (
                        <Tag color="processing">检测中...</Tag>
                      )}
                    </Space>
                  }
                  extra={
                    <Space size="small">
                      {generatedContent && (
                        <>
                          <Dropdown overlay={exportMenu}>
                            <Button
                              size="small"
                              icon={<DownloadOutlined />}
                            />
                          </Dropdown>
                          <Button
                            size="small"
                            icon={<CopyOutlined />}
                            onClick={() => {
                              navigator.clipboard.writeText(generatedContent)
                              message.success('已复制')
                            }}
                          />
                        </>
                      )}
                    </Space>
                  }
                  className="h-full lg:h-full"
                  bodyStyle={{ minHeight: '400px' }}
                >
                  {renderQualityScore()}

                  <div
                    className="generated-content-area"
                    style={{
                      minHeight: '300px',
                      maxHeight: '600px',
                      overflowY: 'auto',
                      padding: '12px',
                      backgroundColor: '#fafafa',
                      borderRadius: '4px',
                      whiteSpace: 'pre-wrap',
                      textAlign: 'right',
                      direction: 'rtl'
                    }}
                  >
                    {generatedContent ? (
                      <div className="markdown-content">
                        {generatedContent}
                      </div>
                    ) : (
                      <Empty
                        description="AI生成的内容将显示在这里"
                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                      />
                    )}
                  </div>
                </Card>
              </Col>

              {/* 右侧优化区 */}
              <Col xs={24} lg={8}>
                <Card
                  title={
                    <Space>
                      <BulbOutlined style={{ color: '#faad14' }} />
                      <Text strong>智能优化</Text>
                    </Space>
                  }
                  className="h-full lg:h-full"
                  bodyStyle={{ minHeight: '400px', maxHeight: '800px', overflowY: 'auto' }}
                >
                  {generatedContent ? (
                    <OptimizationPanel
                      content={generatedContent}
                      title={title}
                      onContentUpdate={(optimizedContent) => {
                        setGeneratedContent(optimizedContent)
                        message.success('优化内容已应用')
                      }}
                    />
                  ) : (
                    <Empty
                      image={Empty.PRESENTED_IMAGE_SIMPLE}
                      description={
                        <div>
                          <Paragraph type="secondary">
                            请先生成内容后再使用智能优化功能
                          </Paragraph>
                        </div>
                      }
                    />
                  )}
                </Card>
              </Col>
            </Row>
            
            {/* 操作按钮栏 */}
            <div className="editor-actions mt-3 md:mt-4 p-3 md:p-4 bg-white rounded-lg">
              <Row gutter={[8, 8]} justify="space-between" className="flex-col md:flex-row">
                <Col xs={24} md="auto">
                  <Space wrap size="small" className="w-full justify-center md:justify-start">
                    <Button
                      icon={<CompareOutlined />}
                      onClick={handleModelComparison}
                      disabled={!content.trim()}
                      size="middle"
                    >
                      <span className="hidden sm:inline">多模型对比</span>
                      <span className="sm:hidden">对比</span>
                    </Button>
                    <Button
                      icon={<SafetyCertificateOutlined />}
                      onClick={() => checkContentQuality(generatedContent)}
                      disabled={!generatedContent}
                      loading={isCheckingQuality}
                      size="middle"
                    >
                      <span className="hidden sm:inline">质量检测</span>
                      <span className="sm:hidden">检测</span>
                    </Button>
                    <Button
                      icon={<HistoryOutlined />}
                      size="middle"
                    >
                      <span className="hidden sm:inline">历史记录</span>
                      <span className="sm:hidden">历史</span>
                    </Button>
                  </Space>
                </Col>
                <Col xs={24} md="auto">
                  <div className="flex justify-center md:justify-end w-full">
                    {isGenerating ? (
                      <Button
                        danger
                        onClick={handleStopGeneration}
                        size="large"
                        block
                        className="md:w-auto"
                      >
                        停止生成
                      </Button>
                    ) : (
                      <Button
                        type="primary"
                        size="large"
                        icon={<SendOutlined />}
                        onClick={handleGenerate}
                        loading={isGenerating}
                        disabled={!content.trim() || !selectedModel}
                        block
                        className="md:w-auto"
                      >
                        开始生成
                      </Button>
                    )}
                  </div>
                </Col>
              </Row>
            </div>
          </TabPane>
          
          {/* 参数设置标签页 */}
          <TabPane
            tab={
              <Space>
                <SettingOutlined />
                <span className="hidden sm:inline">参数设置</span>
                <span className="sm:hidden">参数</span>
              </Space>
            }
            key="params"
          >
            <ParameterPanel
              parameters={parameters}
              onChange={setParameters}
            />
          </TabPane>

          {/* 提示词管理标签页 */}
          <TabPane
            tab={
              <Space>
                <BookOutlined />
                <span className="hidden sm:inline">提示词管理</span>
                <span className="sm:hidden">提示词</span>
              </Space>
            }
            key="prompts"
          >
            <PromptLibrary
              onSelectTemplate={handlePromptSelect}
              onPreviewTemplate={(template) => {
                selectPrompt(template.id)
                setPromptEditorVisible(true)
              }}
            />
          </TabPane>
        </Tabs>
      </div>

      {/* ========== Modals & Drawers ========== */}
      
      {/* 提示词编辑器 */}
      <Drawer
        title="编辑提示词"
        placement="right"
        open={promptEditorVisible}
        onClose={() => setPromptEditorVisible(false)}
        width={720}
      >
        {currentPrompt && (
          <PromptEditor
            value={currentPrompt.systemPrompt}
            template={currentPrompt}
            onChange={(value) => console.log('Prompt changed:', value)}
            onSave={(value) => {
              updatePrompt(currentPrompt.id, { systemPrompt: value })
              message.success('提示词已保存')
              setPromptEditorVisible(false)
            }}
          />
        )}
      </Drawer>
      
      {/* 提示词测试 */}
      <Modal
        title="测试提示词"
        open={promptTesterVisible}
        onCancel={() => setPromptTesterVisible(false)}
        width={1000}
        footer={null}
      >
        <PromptTester />
      </Modal>
      
      {/* 提示词版本历史 */}
      <Drawer
        title="版本历史"
        placement="right"
        open={promptHistoryVisible}
        onClose={() => setPromptHistoryVisible(false)}
        width={600}
      >
        {currentPrompt && (
          <PromptVersionHistory
            promptId={currentPrompt.id}
            onRestore={(version) => {
              message.success('已恢复到该版本')
              setPromptHistoryVisible(false)
            }}
          />
        )}
      </Drawer>
      
      {/* 多模型对比 */}
      <Modal
        title="多模型对比"
        open={modelComparisonVisible}
        onCancel={() => setModelComparisonVisible(false)}
        width={1400}
        footer={null}
        bodyStyle={{ height: '70vh', overflow: 'auto' }}
      >
        <ModelComparison
          prompt={content}
          models={getHealthyModels().map(m => m.id)}
          onSelect={(result) => {
            setGeneratedContent(result)
            setModelComparisonVisible(false)
            message.success('已选择最佳结果')
          }}
        />
      </Modal>

      {/* 热点选择 */}
      <Drawer
        title="选择热点话题"
        placement="right"
        open={hotTopicVisible}
        onClose={() => setHotTopicVisible(false)}
        width={900}
        bodyStyle={{ padding: 0 }}
      >
        <HotTopicPanel 
          onSelect={handleHotTopicSelect}
        />
      </Drawer>
      
      {/* 参数面板 */}
      <Drawer
        title="生成参数设置"
        placement="right"
        open={parameterPanelVisible}
        onClose={() => setParameterPanelVisible(false)}
        width={500}
      >
        <ParameterPanel
          parameters={parameters}
          onChange={setParameters}
        />
      </Drawer>

      {/* 模板选择器 */}
      <Drawer
        title="选择写作模板"
        placement="right"
        open={templateSelectorVisible}
        onClose={() => setTemplateSelectorVisible(false)}
        width={700}
      >
        <div style={{ padding: '0 24px' }}>
          <Alert
            message="提示"
            description="选择一个模板作为创作的基础框架，模板中的变量可以手动替换为实际内容"
            type="info"
            showIcon
            style={{ marginBottom: 20 }}
          />

          <Input.Search
            placeholder="搜索模板..."
            style={{ marginBottom: 16 }}
            allowClear
          />

          <List
            dataSource={templates}
            renderItem={(template: any) => (
              <List.Item
                actions={[
                  <Button
                    type="link"
                    onClick={() => handleApplyTemplate(template)}
                  >
                    使用
                  </Button>
                ]}
              >
                <List.Item.Meta
                  title={
                    <Space>
                      {template.name}
                      <Tag color="blue">{template.category}</Tag>
                      {template.variables && template.variables.length > 0 && (
                        <Tag color="orange">
                          {template.variables.length} 个变量
                        </Tag>
                      )}
                    </Space>
                  }
                  description={template.description || '暂无描述'}
                />
              </List.Item>
            )}
          />
        </div>
      </Drawer>
    </div>
  )
}

export default HotCreatorEditor